import { defineStore } from 'pinia'
import type { UserVO } from '@/api/User.ts'
import { ref } from 'vue'
import {UserApi} from "@/api/UserApi.ts";

export const useUserInfoStore = defineStore('userInfo', () => {
  const currentUser = ref<UserVO | null>(null)

  // 设置用户信息
  function setUser(userInfo: UserVO) {
    currentUser.value = userInfo
  }

  // 清除用户信息
  function clearUser() {
    currentUser.value = null
  }

  // 检查是否为管理员
  const isAdmin = () => {
    return currentUser.value?.role === 'ROLE_SUPER_ADMIN' || currentUser.value?.role === 'ROLE_ADMIN'
  }
  const getUserInfo = async (userId: string) => {
    try {
      const userInfo = await UserApi.getUser(userId)
      userInfo ? setUser(userInfo) : null
      return userInfo
    } catch (error) {
      return null
    }
  }

  return {
    currentUser,
    setUser,
    clearUser,
    isAdmin,
    getUserInfo,
  }
},{
  persist: true
})
